/**
 * Created by EdwardZhu on 22/04/19.
 */
export function autolayout(data) {
    // common functions
    const inSet = (checkSet, nodeId) => {
        return checkSet.findIndex(node => {
            return node.id === nodeId;
        }) >= 0;
    };
    const incr = (nodes, id) => {
        let findNode = nodes.find(node => {
            return node.id === id;
        })
        if (findNode) findNode.count += 1;
        else nodes.push({
            id,
            count: 1,
        });
    };
    const regionLayout = (nodeSet, linkSet, xCenter, yCenter) => {
        let nodes = [];
        linkSet.forEach(link => {
            if (inSet(nodeSet, link.source)) incr(nodes, link.source);
            if (inSet(nodeSet, link.target)) incr(nodes, link.target);
        })
        nodes.sort((a, b) => {
            return b.count - a.count;
        })
        let nodeSize = nodes.length - 1;
        nodes[0].x = xCenter;
        nodes[0].y = yCenter;
        let ang = 2 * Math.PI / nodeSize;
        for (let idx = 1; idx < nodes.length; idx++) {
            nodes[idx].x = xCenter + 2 * Math.cos(idx * ang)
            nodes[idx].y = yCenter + 2 * Math.sin(idx * ang)
            // nodes[idx].x = xCenter
            // nodes[idx].y = yCenter
        }
        return nodes;
    };

    const centerAngular = [0, -Math.PI / 4, -Math.PI / 2, -3 * Math.PI / 4, -Math.PI, 3 * Math.PI / 4, Math.PI / 2, Math.PI / 4];
    // main flow

    // init to zero
    data.nodes.forEach(node => {
        node.x = node.y = 0;
    });

    // category to region
    for (let cIdx = 0; cIdx < 9; cIdx++) {
        let nodeSet = data.nodes.filter(node => {
            return node.category === cIdx;
        });
        let linkSet = data.links.filter(link => {
            return inSet(nodeSet, link.source) || inSet(nodeSet, link.target);
        })
        let xCenter = cIdx > 0 ? (Math.ceil((cIdx - 1) / 8) + 1) * 4 * Math.cos(centerAngular[cIdx - 1]) : 0;
        let yCenter = cIdx > 0 ? (Math.ceil((cIdx - 1) / 8) + 1) * 2 * Math.sin(centerAngular[cIdx - 1]) : 0;
        let nodes = regionLayout(nodeSet, linkSet, xCenter, yCenter);

        console.log(cIdx, xCenter, yCenter);

        // set layout
        nodes.forEach(node => {
            // console.log(node);
            let findNode = data.nodes.find(a => {
                return a.id === node.id;
            })
            if (findNode) {
                findNode.x = node.x;
                findNode.y = node.y;
            }
        })
    }

    // console.log(data.nodes);
    return data;
}

